package com.jakx.controller;

import com.alibaba.fastjson.JSONObject;
import com.jakx.dao.CurlLogMapper;
import com.jakx.dao.CurlLogPojo;
import com.jakx.dao.ProcessMapper;
import com.jakx.dao.ProcessPojo;
import com.jakx.service.AccountServiceImpl;
import com.jakx.service.DemoService;
import com.squareup.okhttp.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@RestController
public class ZhTest {
    public static Map<String, String> map = new HashMap<String, String>();
    MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
    ExecutorService executor = Executors.newFixedThreadPool(5);
    // 接口访问地址
    String createProcessHost = "http://127.0.0.1:8080/ailabs/task/create";
    String createNodeHost = "http://127.0.0.1:8080/ailabs/node/create";
    String updateProcessHost = "http://127.0.0.1:8080/ailabs/task/update";
    // 岗位机构组
    String orgid = "755590";
    String roleid = "5001";
    String grpid = "001";
    // 每次提交任务，业务的数量
    int commitProcessNum = 50;
    @Autowired
    private CurlLogMapper curlLogMapper;

    public static String getMicrosecond() {
        String ft = "yyyy-MM-dd HH:mm:ss.SSSSSS";
        SimpleDateFormat format = new SimpleDateFormat(ft);

        long value = new Date().getTime();
        Date date = new Date(value);

        return format.format(date);
    }

    public static String getNow() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(currentTime);
    }

    @ResponseBody
    @RequestMapping(value = "/run", method = RequestMethod.GET, produces = "text/plain")
    public String start() {

        for (int i = 0; i < 1; i++) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    OkHttpClient client = new OkHttpClient();
                    String name = Thread.currentThread().getName();
                    map.put(name, "start");
                    for (; ; ) {
                        try {
                            String v = map.get(name);
                            if (v.equals("stop")) break;
                            Thread.sleep(100L);
                            List<Tmp> list = new ArrayList<>();
                            try {
                                // 创建业务
                                for (int i = 0; i < commitProcessNum; i++) {
                                    String buscod = uuid();
                                    String flwiid = uuid();
                                    sendCreateProcess(buscod, flwiid, client);
                                    Tmp tmp = new Tmp(buscod, flwiid);
                                    list.add(tmp);
                                }
                                Thread.sleep(2000L);
                                // 创建任务
                                for (Tmp tmp : list) {
                                    sendCreateNode(tmp.getFlwiid(), client);
                                }
                                Thread.sleep(15000L);
                                // 关闭业务
                                for (Tmp tmp : list) {
                                    sendUpdateProcess(tmp.buscod, tmp.getFlwiid(), client);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                continue;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName());
                    }
                }
            });
        }
        return "success";
    }

    private void sendUpdateProcess(String buscod, String flwiid, OkHttpClient client) throws IOException {
        String createProcess = getUpdateProcess(flwiid);
        Request request = new Request.Builder()
                .url(updateProcessHost)
                .post(RequestBody.create(mediaType, createProcess))
                .build();
        // 创建任务
        long processStartTime = System.currentTimeMillis();
        Response response = client.newCall(request).execute();
        long processEndTime = System.currentTimeMillis();
        long processUseTime = processEndTime - processStartTime;
        CurlLogPojo pojo = new CurlLogPojo();
        pojo.setPid(buscod);
        pojo.setUrl(request.urlString());
        pojo.setTxt(createProcess);
        pojo.setUseTime(processUseTime);
        pojo.setNid("");
        curlLogMapper.savePojo(pojo);
    }

    private void sendCreateProcess(String buscod, String flwiid, OkHttpClient client) throws IOException {
        String createProcess = getProcess(buscod, flwiid);
        Request request = new Request.Builder()
                .url(createProcessHost)
                .post(RequestBody.create(mediaType, createProcess))
                .build();
        // 创建任务
        long processStartTime = System.currentTimeMillis();
        Response response = client.newCall(request).execute();
        long processEndTime = System.currentTimeMillis();
        long processUseTime = processEndTime - processStartTime;
        CurlLogPojo pojo = new CurlLogPojo();
        pojo.setPid(buscod);
        pojo.setNid("");
        pojo.setUrl(request.urlString());
        pojo.setTxt(createProcess);
        pojo.setUseTime(processUseTime);
        curlLogMapper.savePojo(pojo);
    }

    private void sendCreateNode(String flwiid, OkHttpClient client) throws IOException {
        String wkiid = uuid();
        String createNode = getNode(wkiid, flwiid);
        Request nodeReq = new Request.Builder()
                .url(createNodeHost)
                .post(RequestBody.create(mediaType, createNode))
                .build();
        long processStartTime = System.currentTimeMillis();
        Response nodeRes = client.newCall(nodeReq).execute();
        long processEndTime = System.currentTimeMillis();
        long processUseTime = processEndTime - processStartTime;

        CurlLogPojo pojo = new CurlLogPojo();
        pojo.setNid(wkiid);
        pojo.setPid("");
        pojo.setUrl(nodeReq.urlString());
        pojo.setTxt(createNode);
        pojo.setUseTime(processUseTime);
        curlLogMapper.savePojo(pojo);
    }

    @ResponseBody
    @RequestMapping(value = "/stop", method = RequestMethod.GET, produces = "text/plain")
    public String stop() {
        System.out.println("xxx");
        for (String key : map.keySet()) {
            map.put(key, "stop");
        }
        return "success";
    }

    private String getUpdateProcess(String flwiid) {
        String str = "{\"flwiid\":\"%s\",\"status\":\"5\",\"reqtim\":\"%s\"}";
        str = String.format(str,flwiid, getNow());
        return str;
    }

    private String getProcess(String budcod, String flwiid) {
        String str = "{\n" +
                "    \"buscod\": \"%s\",\n" +
                "    \"flwiid\": \"%s\",\n" +
                "    \"flwtyp\": \"first_flow\",\n" +
                "    \"trasid\": \"103102\",\n" +
                "    \"strorg\": \"00001-1\",\n" +
                "    \"strusr\": \"755512\",\n" +
                "    \"trschl\": \"00\",\n" +
                "    \"ntsgrp\": \"12016001\",\n" +
                "    \"cusid\": \"c0001\",\n" +
                "    \"cusflg\": \"Z\",\n" +
                "    \"paynum\": \"zhangzuolin\",\n" +
                "    \"drenum\": \"wangrong\",\n" +
                "    \"imgcnt\": 2,\n" +
                "    \"grpflg\": 1,\n" +
                "    \"watflg\": 0,\n" +
                "    \"fstflg\": 0,\n" +
                "    \"amount\": 1000,\n" +
                "    \"cnyno\": \"10\",\n" +
                "    \"strtim\": \"%s\",\n" +
                "    \"reqtim\": \"%s\",\n" +
                "    \"jjcnyno\":\"xxxxjjcnyno\",\n" +
                "    \"jjamount\":\"xxxxjjamount\",\n" +
                "    \"djamout\":\"xxxxdjamout\",\n" +
                "    \"djcnyno\":\"xxxxdjcnyno\",\n" +
                "    \"dzflag\":\"xxxxdzflag\",\n" +
                "    \"actnum\":\"xxxxactnum\",\n" +
                "    \"whtzmcod\":\"11112\"\n" +
                "}";
        str = String.format(str, budcod, flwiid, getMicrosecond(), getMicrosecond()).replace(" ", "");
        return str;
    }

    private String getNode(String wkiid, String flwiid) {
        String str = "{\n" +
                "    \"wkis\": [\n" +
                "        {\n" +
                "            \"wkiid\": \"%s\",\n" +
                "            \"nodnam\": \"AD3\",\n" +
                "            \"flwiid\": \"%s\",\n" +
                "            \"orgid\": \"%s\",\n" +
                "            \"roleid\": [\n" +
                "                \"%s\"\n" +
                "            ],\n" +
                "            \"grpid\": \"%s\",\n" +
                "            \"crttim\": \"%s\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"reqtim\": \"%s\"\n" +
                "}";
        str = String.format(str, wkiid, flwiid, orgid, roleid, grpid, getNow(), getNow()).replace(" ", "");
        return str;
    }

    private String uuid() {
        return String.valueOf(System.currentTimeMillis());
//        return  UUID.randomUUID().toString().replace("-","");
    }

    private class Tmp {
        String buscod;
        String flwiid;

        public Tmp() {
        }

        public Tmp(String buscod, String flwiid) {
            this.buscod = buscod;
            this.flwiid = flwiid;
        }

        public String getBuscod() {
            return buscod;
        }

        public void setBuscod(String buscod) {
            this.buscod = buscod;
        }

        public String getFlwiid() {
            return flwiid;
        }

        public void setFlwiid(String flwiid) {
            this.flwiid = flwiid;
        }
    }
}
